<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<script src="/js/axios.min.js"></script>
<script src="/js/util.js"></script>
<script>
    window.onload = function (){
        findRole();
    }

    function findRole(){
        axios.get("/role/findAll",null).then(e => {
            var info = e.data;
            var str = "";
            for (var i=0;i<info.length;i++){
                var obj = info[i];
                str += `<input type="checkbox" name="roleArray" value="${obj.id}" onclick="getItem()">${obj.name}`;
            }
            $('roleDiv').innerHTML = str;
        })
    }
    function getItem(){
        var idArr = [];
        var chooseList = document.querySelectorAll("#roleDiv [name='roleArray']:checked ")
        for (var i=0;i<chooseList.length;i++){
            idArr.push(chooseList[i].value);
        }

        return idArr;
    }

    function findGrade(){
        var roleArray = getItem();
        if (roleArray.length == 0){
            $('gradeDiv').innerHTML = "";
            return;
        }

        var params = new URLSearchParams();
        params.append("roleArray",roleArray);

        axios.post("/grade/findByRoleArray",params).then(e => {
            var info = e.data;
            var str = "";
            for (var i=0;i<info.length;i++){
                str += info[i].name+"、"
            }
            $('gradeDiv').innerHTML = str;
        })
    }

    function addUser(){
        var params = new URLSearchParams();
        params.append("code",$('code').value);
        params.append("name",$('name').value);
        params.append("roleArray",getItem());

        axios.post("/user/add",params).then(e => {
            if (e.data == 'ok'){
                location.href = "/user/user.html"
            }
        })

    }
</script>
<body>
    <h2>添加用户</h2>
    用户名:<input type="text" id="code"><br>
    真实姓名:<input type="text" id="name"><br>
    拥有角色:<div id="roleDiv" style="width: 300px" onclick="findGrade()"></div>
    拥有的权限:<div id="gradeDiv"></div>
    <input type="button" value="添加" onclick="addUser()">
</body>
</html>